<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;
use tree\Tree;

class Plan extends Controller
{
    /**
     * 将禁止接单的渠道商恢复正常
     * */
    public function setChannelNormal()
    {
        $zero_time = strtotime(date('Y-m-d'));
        $now_time = time();
        $ids = Db::name('user')->whereBetween('channel_reset_time', [$zero_time, $now_time])->where(['channel_is_normal' => 0, 'channel_is_send_order' => 0])->column('id');
        if ($ids) {
            $user_data = [
                'channel_reset_time' => $now_time,
                'channel_is_normal' => 1,
                'channel_is_send_order' => 1
            ];
            $res = Db::name('user')->whereIn('id', $ids)->update($user_data);
            if ($res) {
                file_put_contents(RUNTIME_PATH . 'setChannelNormal.log', date('Y-m-d H:i:s') . ' 成功将 ' . count($ids) . ' 个渠道商恢复正常，ids => ' . implode(',', $ids) . PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents(RUNTIME_PATH . 'setChannelNormal.log', date('Y-m-d H:i:s') . ' 将 ' . count($ids) . ' 个渠道商恢复正常失败，ids => ' . implode(',', $ids) . PHP_EOL, FILE_APPEND);
            }
        } else {
            file_put_contents(RUNTIME_PATH . 'setChannelNormal.log', date('Y-m-d H:i:s') . ' 没有需要恢复的渠道商' . PHP_EOL, FILE_APPEND);
        }
    }

    /**
     * 查询订单表是否有【服务中】但是超过1小时仍然未接单的订单，重新变成【申请中】状态
     * */
    public function checkAndSetOrder()
    {
        $now = time();
        $timeout = $now - 3600; // 超过1小时未接单

        // 查找“服务中”状态但未接单并超过1小时的订单
        $order_ids = Db::name('order')
            ->where('status', 2) // 服务中
            ->where('is_accept', 0) // 未接单
            ->where('update_time', '<', $timeout)
            ->column('id');
        if ($order_ids) {
            $data = [
                'status' => 1,
                'update_time' => $now,
            ];
            Db::name('order')->whereIn('id', $order_ids)->update($data);

            $remark = date('Y-m-d H:i:s') . ' 成功将 ' . count($order_ids) . ' 个订单重新变成【申请中】状态，ids => ' . implode(',', $order_ids);
            echo $remark;
            file_put_contents(RUNTIME_PATH . 'checkAndSetOrder.log', $remark . PHP_EOL, FILE_APPEND);
        }
    }

}
